package com.zllkj.mm.module.moment

import android.content.Intent
import android.graphics.Bitmap
import android.media.ThumbnailUtils
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.kennyc.bottomsheet.BottomSheetListener
import com.kennyc.bottomsheet.BottomSheetMenuDialogFragment
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.orhanobut.logger.Logger
import com.zllkj.mm.R
import com.zllkj.mm.adapter.PushPostAdapter
import com.zllkj.mm.api.network.RetrofitHelper
import com.zllkj.mm.api.network.RxHelper
import com.zllkj.mm.api.network.subscriber.ProgressSubscriber
import com.zllkj.mm.api.remote.Api
import com.zllkj.mm.base.BaseFragment
import com.zllkj.mm.base.BaseTitleFragment
import com.zllkj.mm.common.L
import com.zllkj.mm.model.entity.DynamicSubscriptionVo
import com.zllkj.mm.model.entity.FileUrlEntity
import com.zllkj.mm.module.goods.vm.ItemPostImageVM
import com.zllkj.mm.module.home.fragments.PoiNearSearchResultFragment
import com.zllkj.mm.module.home.fragments.vm.ItemSearchPoiResultVM
import com.zllkj.mm.module.main.MainActivity
import com.zllkj.mm.util.JsonUtil
import com.zllkj.mm.util.common.AppUtils
import com.zllkj.mm.util.common.FileUtils
import com.zllkj.mm.util.common.FormatUtil
import com.zllkj.mm.util.common.GlideEngine
import kotlinx.android.synthetic.main.fragment_push_post.*
import kotlinx.android.synthetic.main.fragment_push_post.view.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.io.FileOutputStream


class PushPostFragment : BaseTitleFragment() {
    var SYSTEM_IMAGE = 111
    var postType = 2
    lateinit var adapter: PushPostAdapter
    var datasPushImages = ArrayList<ItemPostImageVM>()
    var curLocation = ItemSearchPoiResultVM()
    var validityPeriod = 0
    var unit = 0

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_push_post
    }

    fun reset() {
        ed_push_post_content.setText("")
        datasPushImages.clear()
        datasPushImages.add(ItemPostImageVM().apply {
            this.isAddPosition = true
        })
        adapter.notifyDataSetChanged()
        mRootView.ed_push_post_content.setText("")
        mRootView.tv_push_post_location.text = "请选择地址"
        mRootView.ed_push_post_money.setText("")
        curLocation = ItemSearchPoiResultVM()
        AppUtils.putFragmentData("location",null)
        mRootView.ll_free_area_money.visibility = View.GONE
        mRootView.ll_free_area_time.visibility = View.GONE
        mRootView.tv_push_post_time.text = "请选择时效"
        mRootView.tv_push_post_switch_type.text = "切换闲时状态"
        postType = 2
    }

    fun goToSelectPic() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofAll())
                .isWithVideoImage(true)
                .selectionMode(PictureConfig.SINGLE)
                .imageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(p0: MutableList<LocalMedia>?) {
                        p0?.get(0)?.let {

                            var bean = ItemPostImageVM()
                            bean.mediaData = it
                            if (datasPushImages.size == 9) {
                                datasPushImages.removeAt(8)
                            }
                            if (PictureMimeType.isHasVideo(it.mimeType)) { //是个视频

                                L.showToast("视频上传中...")

                                datasPushImages.clear() // 如果是视频的话 就保留一个
                                bean.itemType = 1
                                bean.path = it.path
                                bean.isAddPosition = false
                                bean.videoDuration = FormatUtil.formatDurationTime(it.duration).toString()
                                upLoadVideo(requireContext().contentResolver.getType(Uri.parse(it.path)), it.realPath)
                            } else {
                                bean.itemType = 0
                                bean.path = it.path
                                bean.isAddPosition = false
                                uploadImage(requireContext().contentResolver.getType(Uri.parse(it.path)), it.realPath, 0)
                            }
                            datasPushImages.add(0, bean)
                            adapter.notifyDataSetChanged()
                        }
                    }

                    override fun onCancel() {

                    }

                });
    }

    override fun onResume() {
        super.onResume()

        if (AppUtils.getFragmentData("location") != null) {
            curLocation = AppUtils.getFragmentData("location") as ItemSearchPoiResultVM
            mRootView.tv_push_post_location.text = curLocation.detailAddress
        }
    }

    fun upLoadVideo(fileType: String, url: String) {

        val file = File(url)
        val requestFile = RequestBody.create(MediaType.parse(fileType), file)
        val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
        val descriptionString = "video"
        val description = RequestBody.create(
                MultipartBody.FORM, descriptionString)

        var bitmap = ThumbnailUtils.createVideoThumbnail(url, MediaStore.Video.Thumbnails.MINI_KIND)

        var imageFile = File(FileUtils.getThumbnailPath(requireContext()) + "/" + System.currentTimeMillis() + ".jpg")


        try {
            var ops = FileOutputStream(imageFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ops)
            ops.flush()
            ops.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        addSubscribe(RetrofitHelper.getInstance().uploadFileRetrofitClient.create(Api::class.java).uploadVideo(body, description).compose<FileUrlEntity>(RxHelper.defaultHandleResult<FileUrlEntity>()).subscribe(object : ProgressSubscriber<FileUrlEntity>(context) {
            override fun onSucc(t: FileUrlEntity?) {

                t?.fileUrl?.let {
                    L.showToast("视频上传成功")
                    datasPushImages[0].videoUrl = t?.fileUrl
                }

            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }

            override fun onStart() {
                super.onStart()
                L.showToast("视频上传中...")
            }
        }))

        uploadImage("image/*", imageFile.absolutePath, 0)

    }

    fun uploadImage(fileType: String, url: String, ninePosition: Int) {
        val file = File(url)
        val requestFile = RequestBody.create(MediaType.parse(fileType), file)
        val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
        val descriptionString = "image"
        val description = RequestBody.create(
                MultipartBody.FORM, descriptionString)

        addSubscribe(RetrofitHelper.getInstance().uploadFileRetrofitClient.create(Api::class.java).uploadImage(body, description).compose<FileUrlEntity>(RxHelper.defaultHandleResult<FileUrlEntity>()).subscribe(object : ProgressSubscriber<FileUrlEntity>(context) {
            override fun onSucc(t: FileUrlEntity?) {
                t?.fileUrl?.let {
                    datasPushImages[ninePosition].uploadSuccessUrl = t?.fileUrl

                }
            }

            override fun onError(e: Throwable?) {
                super.onError(e)
            }
        }))
    }

    override fun loadData() {
        super.loadData()

        setCommonTitle("发布")
        setRightBtn("发布", View.OnClickListener {
            if (TextUtils.isEmpty(mRootView.ed_push_post_content.text)) {
                L.showToast("请输入内容")
            } else {
                addSubscribe(RetrofitHelper.getInstance().api.addPost((HashMap<String, Any>().apply {
                    var imageList = ArrayList<String>()
                    datasPushImages.map {
                        it.uploadSuccessUrl?.let { serverImage -> imageList.add(serverImage) }
                    }
                    this["address"] = curLocation.detailAddress
                    this["city"] = curLocation.city
                    this["content"] = ed_push_post_content.text.toString()
                    this["district"] = curLocation.adName
                    this["dynamicType"] = postType
                    this["price"] = if (postType == 1) { Integer.parseInt( mRootView.ed_push_post_money.text.toString() ) * 100 } else 0
                    this["topic"] = ""
                    this["validityPeriod"] = validityPeriod
                    this["videoUrl"] = if (datasPushImages[0] != null) datasPushImages[0].videoUrl else ""
                    this["longitude"] = AppUtils.lng
                    this["latitude"] = AppUtils.lat
                    this["pic"] = if (imageList.size > 0) JsonUtil.GsonString(imageList).replace("\"", "").replace("[", "").replace("]", "") else ""
                    this["unit"] = unit
                    this["province"] = curLocation.provinceName
                })).compose<DynamicSubscriptionVo>(RxHelper.defaultHandleResult<DynamicSubscriptionVo>()).subscribe(object : ProgressSubscriber<DynamicSubscriptionVo>(context) {
                    override fun onSucc(t: DynamicSubscriptionVo?) {

                        requireContext().sendBroadcast(Intent(BaseFragment.ACTION_FRAGMENT_UPDATE).apply { putExtra(AppUtils.KEY_OF_REFRESH_MOMENT_LIST,true) })

                        var act = requireActivity() as MainActivity
                        act.switchTab(1)
                        reset()
                    }

                    override fun onError(e: Throwable?) {
                        super.onError(e)
                    }
                }))
            }
        })

        mRootView.tv_push_post_switch_type.setOnClickListener {
            if (postType == 2) {
                mRootView.ll_free_area_money.visibility = View.VISIBLE
                mRootView.ll_free_area_time.visibility = View.VISIBLE
                mRootView.tv_push_post_switch_type.text = "切换普通状态"
                postType = 1
            } else {
                mRootView.ll_free_area_money.visibility = View.GONE
                mRootView.ll_free_area_time.visibility = View.GONE
                mRootView.tv_push_post_switch_type.text = "切换闲时状态"
                postType = 2
                mRootView.tv_price_unit.text = ""
                mRootView.ed_push_post_money.setText("")
            }

        }
        mRootView.tv_push_post_location.setOnClickListener {
            addFragment(PoiNearSearchResultFragment())
        }

        mRootView.tv_push_post_time.setOnClickListener {
            var listener = object : BottomSheetListener {
                override fun onSheetDismissed(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?, dismissEvent: Int) {

                }

                override fun onSheetItemSelected(bottomSheet: BottomSheetMenuDialogFragment, item: MenuItem, `object`: Any?) {
                    mRootView.tv_push_post_time.text = item.title
                    when (item.itemId) {
                        R.id.menu_post_in_today -> {
                            validityPeriod = 1
                        }
                        R.id.menu_post_in_those_three_day -> {
                            validityPeriod = 2
                        }
                        R.id.menu_post_in_one_week -> {
                            validityPeriod = 3
                        }
                        R.id.menu_post_in_one_month -> {
                            validityPeriod = 4
                        }
                        R.id.menu_post_in_one_year -> {
                            validityPeriod = 5
                        }
                        R.id.menu_post_in_any_time -> {
                            validityPeriod = 6
                        }

                    }
                }

                override fun onSheetShown(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?) {

                }

            }
            BottomSheetMenuDialogFragment.Builder(context = requireContext(),
                    sheet = R.menu.menu_post_time_way,
                    listener = listener,
                    title = "请选择时效",
                    `object` = "")
                    .show(childFragmentManager)
        }

        mRootView.tv_price_unit.setOnClickListener {
            var listener = object : BottomSheetListener {
                override fun onSheetDismissed(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?, dismissEvent: Int) {

                }

                override fun onSheetItemSelected(bottomSheet: BottomSheetMenuDialogFragment, item: MenuItem, `object`: Any?) {
                    mRootView.tv_price_unit.text = item.title
                    if (item.itemId == R.id.menu_post_money_unit_day) {
                        unit = 2
                    } else if (item.itemId == R.id.menu_post_money_unit_one_time) {
                        unit = 1
                    } else if (item.itemId == R.id.menu_post_money_unit_week) {
                        unit = 3
                    }
                }

                override fun onSheetShown(bottomSheet: BottomSheetMenuDialogFragment, `object`: Any?) {

                }

            }
            BottomSheetMenuDialogFragment.Builder(context = requireContext(),
                    sheet = R.menu.menu_post_money_unit,
                    listener = listener,
                    title = "请选择单位",
                    `object` = "")
                    .show(childFragmentManager)
        }

        datasPushImages.add(ItemPostImageVM().apply { this.isAddPosition = true })
        adapter = PushPostAdapter(R.layout.item_push_post_image, datasPushImages)
        mRootView.rv_gril_add_post.layoutManager = GridLayoutManager(requireContext(), 3)
        mRootView.rv_gril_add_post.adapter = adapter
        adapter.setOnItemChildClickListener { baseQuickAdapter, view, i ->

            if (datasPushImages.size == 1) {
                datasPushImages[0] = ItemPostImageVM().apply {
                    this.isAddPosition = true
                }
            } else if (datasPushImages.size == 9) {
                var hasAddIcon = false
                datasPushImages.map {
                    hasAddIcon = it.isAddPosition
                }
                if (!hasAddIcon) {
                    datasPushImages.removeAt(i)
                    datasPushImages.add(8, ItemPostImageVM().apply { this.isAddPosition = true })
                } else {
                    datasPushImages.removeAt(i)
                }
            } else {
                datasPushImages.removeAt(i)
            }
            adapter.notifyDataSetChanged()
        }
        adapter.setOnItemClickListener { baseQuickAdapter, view, i ->
            if (datasPushImages[i].isAddPosition) {
                goToSelectPic()
            }
        }

    }
}